package com.java.code.web.controller;

import com.java.code.http.JavaHttpRequest;
import com.java.code.utils.date.DateUtils;
import com.java.code.utils.encrypt.Sha1Util;
import com.java.code.utils.uuid.UUID;
import com.java.code.web.entity.WechatToken;
import com.java.code.web.tencent.entity.AccessTokenOutData;
import com.java.code.web.tencent.entity.JsapiOutData;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.springframework.web.bind.annotation.*;

import java.util.*;

/**
 * @author weichuanyuan
 * @version 1.0
 * @date 2021/9/27 17:48
 */
@RestController
@RequestMapping("/tencent")
public class TencentController {
    //测试号的信息
    //https://mp.weixin.qq.com/debug/cgi-bin/sandboxinfo?action=showinfo&t=sandbox/index
    public final static String appid = "wxd896bac0ca9a7584";
    public final static String appsecret = "f69dd3eaabd98b560e09501e0fdfb056";
    public final static String tokenUrl = "https://api.weixin.qq.com/cgi-bin/token";
    public final static String ticketUrl = "https://api.weixin.qq.com/cgi-bin/ticket/getticket";
    public final static String domainUrl = "http://6xj3iz.natappfree.cc/news/NewsCenter";//域名

    public static Map<String, Map<String, Object>> tokens = new HashMap<>();

    @GetMapping("/wechatCheck")
    public String wechatCheck(@PathVariable String signature,
                              @PathVariable String timestamp,
                              @PathVariable String nonce,
                              @PathVariable String echostr) {

        System.out.println("signature=" + signature);
        System.out.println("timestamp=" + timestamp);
        System.out.println("nonce=" + nonce);
        System.out.println("echostr=" + echostr);

        return echostr;
    }

    @RequestMapping("/getWechatToken")
    public WechatToken getWechatToken() throws Exception {
        if (tokens.containsKey("config")) {
            return (WechatToken) tokens.get("config").get("signature");
        }

        List<NameValuePair> params = new ArrayList<>();
        params.add(new BasicNameValuePair("grant_type", "client_credential"));
        params.add(new BasicNameValuePair("appid", appid));
        params.add(new BasicNameValuePair("secret", appsecret));

        //获取token
        AccessTokenOutData accessTokenOutData = JavaHttpRequest.httpGet(tokenUrl, params, AccessTokenOutData.class);

        tokens.put("token",
                new HashMap<String, Object>() {
                    {
                        put(accessTokenOutData.getAccess_token(),
                                DateUtils.subSeconds(new Date(), Integer.parseInt(accessTokenOutData.getExpires_in())));
                    }
                }
        );
        //获取ticket
        params = new ArrayList<>();
        params.add(new BasicNameValuePair("access_token", accessTokenOutData.getAccess_token()));
        params.add(new BasicNameValuePair("type", "jsapi"));
        JsapiOutData jsapiOutData = JavaHttpRequest.httpGet(ticketUrl, params, JsapiOutData.class);
        tokens.put("ticket",
                new HashMap<String, Object>() {
                    {
                        put(jsapiOutData.getTicket(),
                                DateUtils.subSeconds(new Date(), Integer.parseInt(jsapiOutData.getExpires_in())));
                    }
                }
        );
        //生成签名
        String noncestr = UUID.randomUUID().toString().replace("-", "");//随机字符串
        String timestamp = String.valueOf(DateUtils.secondTimestamp(new Date()));//时间戳,精确到秒
        SortedMap<String, String> map = new TreeMap<>();
        map.put("jsapi_ticket", jsapiOutData.getTicket());
        map.put("noncestr", noncestr);
        map.put("timestamp", timestamp);
        map.put("url", domainUrl);
        String signature = Sha1Util.createSHA1Sign(map);//对string1进行sha1签名，得到signature

        WechatToken wechatToken = new WechatToken();
        wechatToken.setAppId(appid);
        wechatToken.setDebug(true);
        wechatToken.setNonceStr(noncestr);
        wechatToken.setSignature(signature);
        wechatToken.setTimestamp(timestamp);

        //前端需要的信息
        tokens.put("config",
                new HashMap<String, Object>() {
                    {
                        put("signature", wechatToken);
                    }
                }
        );
        return wechatToken;
    }


}
